#coding=utf-8
import email
import imaplib
import os

from apscheduler.schedulers.blocking import BlockingScheduler

from utils import sga_psutil

host = 'imap.aliyun.com'
username = 'musiclef@aliyun.com'
password = 'Livcop016!'


class kk:
    check_cnt = 0

k = kk()


def startssh():
    if sga_psutil.existProcess('privoxy'):
        return
    else:
        sga_psutil.exeCommand('/home/hysga/bin/privoxy3/privoxy /home/hysga/bin/privoxy3/myconfig')


def stopssh():
    sga_psutil.exeCommand('killall -9 privoxy')


def exist_connection():
    connections = os.popen('netstat -anp|grep privoxy|grep ESTABLISHED').read()
    cnt = connections.count('\n')
    if cnt > 0:
        return 1
    else:
        return 0


def write_pid():
    pid = str(os.getpid())
    f = open('athena.pid', 'w')
    f.write(pid)
    f.close()

def main():
    if exist_connection() == 1:
        k.check_cnt = 0
        return
    else:
        k.check_cnt += 1

    if k.check_cnt > 3:
        stopssh()

    conn = imaplib.IMAP4_SSL(host)
    try:
        conn.login(username,password)
        result, message  = conn.select()
        type, data = conn.search(None, 'ALL')
        msgList = data[0].split()
        for num in data[0].split():
            type,data = conn.fetch(msgList[len(msgList)-1],'(RFC822)')
            msg = email.message_from_string(data[0][1])
            subject = email.Header.decode_header(msg['Subject'])
            subject = subject[0][0]
            if subject == 'startssh':
                conn.store(num, '+FLAGS', '\\Deleted')
                startssh()
                k.check_cnt = 0
        conn.expunge()
        conn.logout()
    except Exception,e:
        print 'login error: %s' % e
        conn.close()
    print 'end'

scheduler = BlockingScheduler()
scheduler.add_job(main, "cron", minute="*/3")
try:
    scheduler.start()
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()
